package com.contact.util.util.conversion;

import java.math.BigDecimal;

import org.apache.commons.beanutils.converters.AbstractConverter;
import org.apache.commons.beanutils.converters.BigDecimalConverter;

import com.contact.util.StringUtils;

/**
 * Handles nulls and empty values without freaking out
 */
public class RobustBigDecimalConverter extends AbstractConverter {

    private final transient BigDecimalConverter converter;

    public RobustBigDecimalConverter() {
        super();
        this.converter = new BigDecimalConverter();
    }

    @SuppressWarnings("rawtypes")
    @Override
    protected Object convertToType(Class c, Object value) throws Throwable {
        if (value == null) {
            return null;
        }
        if (value instanceof String && StringUtils.isEmpty((String) value)) {
            return null;
        }
        return converter.convert(c, value);
    }

    @SuppressWarnings("rawtypes")
    @Override
    protected Object handleMissing(Class c) {
        return null;
    }

    @Override
    protected Class<?> getDefaultType() {
        return BigDecimal.class;
    }

}
